package io.xxx.omni.osc.metric

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.actuate.health.AbstractHealthIndicator
import org.springframework.boot.actuate.health.Health
import org.springframework.stereotype.Component
import java.util.concurrent.ThreadPoolExecutor

@Component
class ThreadPoolMetrics : AbstractHealthIndicator() {

    @Autowired
    private lateinit var executor: ThreadPoolExecutor

    override fun doHealthCheck(builder: Health.Builder) {
        val activeCount = executor.activeCount
        val maximumPoolSize = executor.maximumPoolSize
        val queue = executor.queue

        val rate = activeCount.toDouble() / maximumPoolSize

        val details = HashMap<String, Any>()
        details["rate"] = rate
        details["corePoolSize"] = executor.corePoolSize
        details["maximumPoolSize"] = maximumPoolSize
        details["queueSize"] = queue.size
        details["activeCount"] = activeCount
        details["completedTaskCount"] = executor.completedTaskCount
        details["poolSize"] = executor.poolSize
        details["largestPoolSize"] = executor.largestPoolSize
        details["remainingCapacity"] = queue.remainingCapacity()
        builder.withDetails(details)
        if (rate > 0.8) builder.down() else builder.up()
    }
}